<template>
  <div>
    <div class="search-bar" style="display: flex; justify-content: flex-end; margin-bottom: 20px;">
      <el-input v-model="posttitle" style="width: 300px; margin-right: 10px;" clearable @clear="clearSearch" placeholder="请输入想搜索的帖子标题？"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button type="danger" icon="el-icon-edit-outline" @click="sendPost">我要发帖</el-button>
      <!-- 在线讨论区跳转按钮 -->
      <el-button type="success" icon="el-icon-chat-line-round" @click="goToDiscussion">在线讨论区</el-button>
    </div>

    <el-row :gutter="15" class="content-row">
      <el-col :span="4" class="sidebar">
        <h4 class="section-title">
          <i class="el-icon-collection"></i>
          <span class="section-title-text">帖子类型</span>
        </h4>
        <div class="sidebar-content">
          <p class="xw-enlarge" v-for="type in ['全部', ...postTypeData]" :key="type" @click="changeType(type)">
            <i class="el-icon-collection"></i>
            <span>{{ type }}</span>
          </p>
        </div>
      </el-col>


      <el-col :span="13" class="main-content">
        <ul class="infinite-list" v-infinite-scroll="load">
          <li v-for="(item, index) in tableData.slice(0, count)" :key="index" class="post-item">
            <div class="post-item-content">
              <h4 class="ellipsis post-title" @click="toDetail(item)">{{ item.title }}</h4>
              <p class="ellipsis post-description" v-html="item.content"></p>
              <p class="post-meta">
                <i class="el-icon-s-custom"></i>
                <span>{{ item.sendUserName }}</span>
                <span>{{ item.sendTime | dateFormatHms }}</span>
                <el-tag class="post-tag" type="mini">{{ item.type }}</el-tag>
              </p>
            </div>
          </li>
        </ul>
      </el-col>

      <el-col :span="4" class="sidebar high-rank">
        <h4 class="section-title">
          <i class="el-icon-trophy"></i>
          <span class="section-title-text">高赞帖子</span>
        </h4>
        <div class="high-rank-content">
          <ul>
            <li v-for="(post, index) in highRankPosts" :key="index" class="high-rank-item">
              <h4 class="ellipsis xw-enlarge"
                  @click="toDetailthumb(post)"
                  style="cursor: pointer; color: rgba(255,64,109,0.93); font-weight: bold;">
                {{ post.title }}
              </h4>
            </li>
          </ul>
        </div>
      </el-col>
    </el-row>
    <!-- 分页部分 -->
    <div class="pagination-container">
      <p class="pagination-info">
        共 {{ total }} 条 / 第 {{ pageRequest.pageNum }} 页 / 共 {{ totalPages }} 页
      </p>
      <ul class="pagination">
        <li
            class="pagination-button"
            :class="{ disabled: pageRequest.pageNum === 1 }"
            @click="goToPage(1)"
        >
          首页
        </li>
        <li
            class="pagination-button"
            :class="{ disabled: pageRequest.pageNum === 1 }"
            @click="goToPage(pageRequest.pageNum - 1)"
        >
          上一页
        </li>
        <li
            v-for="page in visiblePages"
            :key="page"
            :class="{ active: pageRequest.pageNum === page, 'pagination-button': true }"
            @click="goToPage(page)"
        >
          {{ page }}
        </li>
        <li
            class="pagination-button"
            :class="{ disabled: pageRequest.pageNum === totalPages }"
            @click="goToPage(pageRequest.pageNum + 1)"
        >
          下一页
        </li>
        <li
            class="pagination-button"
            :class="{ disabled: pageRequest.pageNum === totalPages }"
            @click="goToPage(totalPages)"
        >
          尾页
        </li>
      </ul>
    </div>
    <SendPost ref="SendPost" @sendSuccess="load"></SendPost>

    <my-drawer ref="MyDrawer" :row="selectRow" @saveOrUpdate="update">
      <template #default>
        <el-form label-position="top" class="post-form">
          <el-form-item label='标题'>
            <el-input placeholder='请输入发布的帖子标题'
                      v-model='selectRow.title'></el-input>
          </el-form-item>
          <el-form-item label="帖子类型">
            <el-select v-model="selectRow.type" placeholder="请选择帖子类型">
              <el-option label="C语言" value="C语言"></el-option>
              <el-option label="HTML" value="HTML"></el-option>
              <el-option label="JAVA" value="JAVA"></el-option>
              <el-option label="Python" value="Python"></el-option>
              <el-option label="云计算" value="云计算"></el-option>
              <el-option label="软件工程" value="软件工程"></el-option>
              <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
              <el-option label="信息安全" value="信息安全"></el-option>
              <el-option label="大数据" value="大数据"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='发布内容'>
            <vue-editor v-model="selectRow.content"></vue-editor>
          </el-form-item>
        </el-form>
      </template>
    </my-drawer>
  </div>
</template>

<script>
import SendPost from "@/components/SendPost.vue";
import MyDrawer from "@/components/MyDrawer.vue";
import { VueEditor } from "vue2-editor";

export default {
  data() {
    return {
      posttitle: '',
      count: 5,
      tableData: [],
      postTypeData: [],
      highRankPosts: [], // 高赞帖子的列表
      pageRequest: {
        pageNum: 1,
        pageSize: 5,
        q: {}
      },
      total: 0,
      totalPages: 0, // 总页数
      user: JSON.parse(localStorage.getItem("user")),
      // 用于存储选中的文章
      selectRow: {
        title: '',
        type: '',
        content: ''
      },
    };
  },
  mounted() {
    this.load()
  },
  components: {
    visiblePages() {
      const pages = [];
      const {pageNum, totalPages} = this.pageRequest;
      const maxVisible = 5; // 显示的最大页码数量
      const start = Math.max(1, pageNum - 2);
      const end = Math.min(start + maxVisible - 1, totalPages);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      return pages;
    },
    MyDrawer,
    SendPost,
    VueEditor
  },
  methods: {
    toDetailthumb(post) {
   this.$router.push({name: 'PostCodeDetail', params: {id: post.linkId}});
    },
    toDetail(item) {
      this.$router.push({name: 'PostCodeDetail', params: {id: item.id}});
    },
    goToDiscussion() {
      window.location.href = 'http://localhost:8700/onDiscussion';
    },

    sendPost() {
      this.$refs.SendPost.open()
    },
    clearSearch() {
      this.posttitle = '';  // 清空输入框
      this.pageRequest.q = {};  // 清空搜索条件
      this.load();  // 重新加载数据
    },

    search() {
      this.pageRequest.pageNum = 1;  // 重置页码
      if (this.posttitle.trim() === '') {
        // 如果没有输入标题，清空查询条件，显示所有帖子
        this.pageRequest.q = {};
      } else {
        // 如果输入了标题，按照标题搜索
        this.pageRequest.q.title = this.posttitle;
      }
      this.load();  // 重新加载数据
    },
    edit(title) {
      // 根据标题查找文章并进行编辑
      const post = this.tableData.find(item => item.title === title);
      if (post) {
        this.selectRow = post;
        this.$refs.MyDrawer.open(this.selectRow);
      }
    },
    update() {
      this.request.post("/postCode", this.selectRow).then(res => {
        if (res.code === '200') {
          this.messageSuccess("修改成功");
          this.$refs.MyDrawer.close();  // 关闭抽屉
          this.load();  // 重新加载数据
        } else {
          this.messageError(res.msg);  // 显示错误消息
        }
      });
    },

    changeType(type) {
      if (type === '全部') {
        this.pageRequest.q.type = '';  // 清空类型筛选
      } else {
        this.pageRequest.q.type = type;  // 设置为选中的类型
      }
      this.load();  // 重新加载帖子
    },
    extractTextWithoutImages(htmlContent) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlContent, 'text/html');
      return doc.body.textContent || ""; // 提取纯文本内容
    },
    load() {
      this.request.post("/postCode/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          // 遍历数据，提取纯文本，移除图片
          this.tableData = res.data.list.map(item => ({
            ...item,
            content: this.extractTextWithoutImages(item.content) // 提取纯文本
          }));

          this.total = res.data.total;
          this.totalPages = Math.ceil(this.total / this.pageRequest.pageSize);
        }
      });

      // 加载高赞帖子数据
      this.request.get("/thumbs/highRankPosts").then(res => {
        if (res.code === '200') {
          this.highRankPosts = res.data;
        }
      });
      this.request.get("/postCode/postType").then(res => {
        if (res.code === '200') {
          this.postTypeData = res.data;
        }
      });
    },
    goToPage(page) {
      if (page < 1 || page > this.totalPages || page === this.pageRequest.pageNum) {
        return;
      }
      this.pageRequest.pageNum = page;
      this.load();
    },
    errorHandler() {
      // 头像加载失败时返回灰色
      return true;
    },
    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      this.load();
    },
    handleSizeChange(size) {
      this.pageRequest.pageSize = size;
      this.load();
    },
  }
}
</script>

<style scoped>
.search-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.search-btn, .post-btn {
  margin-left: 10px;
  padding: 8px 15px;
}

.search-btn {
  background-color: #409EFF;
  border-color: #409EFF;
}

.post-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.content-row {
  display: flex;
  justify-content: center;
}

.sidebar {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sidebar .section-title {
  font-size: 18px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.sidebar .section-title-text {
  margin-left: 8px;
}

.sidebar-content {
  max-height: 50vh;
  padding: 10px;
}

.sidebar-content p {
  cursor: pointer;
  margin: 8px 0;
  padding: 8px;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

.sidebar-content p:hover {
  background-color: #f0f0f0;
}

.main-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative; /* 设置为相对定位 */
  //height:120vh;
}

.infinite-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.post-item {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #e4e6eb;
}

.post-item-content {
  width: 40%;
}

.post-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
}

.post-description {
  font-size: 14px;
  color: #777;
  margin-top: 5px;
}

.post-meta {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}

.post-tag {
  margin-left: 10px;
}

.post-image img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.el-tag {
  transition: background-color 0.3s ease, color 0.3s ease;
}

.el-tag:hover {
  background-color: #f56c6c;
  color: #fff;
}


.pagination-container {
  text-align: center;
  margin-top: 20px;
}

.pagination-info {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.pagination {
  list-style: none;
  padding: 0;
  display: inline-block;
}

.pagination li {
  display: inline-block;
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #007bff;
}

.pagination li.active {
  background-color: #007bff;
  color: #fff;
  border-color: #007bff;
}

.pagination li.disabled {
  color: #ccc;
  cursor: not-allowed;
  border-color: #eee;
}

.pagination li:hover:not(.active):not(.disabled) {
  background-color: #f0f0f0;
}


.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.post-description {
  display: -webkit-box;
  -webkit-line-clamp: 1; /* 显示一行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

</style>
